package com.aneliya.framework.mvc.controller;

import java.util.Hashtable;

public class Controller implements IController {
	
	private static Controller instance;
	public static Controller getInstance() {
		if (instance == null) {
			instance = new Controller();
		}
		return instance;
	}

	private Hashtable<String, Class<?>> commandRegister;
	
	protected Controller() {
		commandRegister = new Hashtable<String, Class<?>>();
	}

	public void registerCommand(String eventType, Class<?> commandClass) 
			throws Exception {
		if (!commandRegister.containsKey(eventType)) {
			commandRegister.put(eventType, commandClass);
		} else {
			throw new Exception("There is already a registered command for event type: " + eventType);
		}
	}
	
	public void removeCommand(String eventType) throws Exception {
		if (commandRegister.containsKey(eventType)) {
			commandRegister.remove(eventType);
		} else {
			throw new Exception("There is no registered command for event type: " + eventType);
		}
	}
	
	public void dispatchMVCEvent(MVCEvent event) 
			throws InstantiationException, IllegalAccessException {
		if (commandRegister.containsKey(event.type)) {
			Class<?> commandClass = commandRegister.get(event.type);
			ICommand command = (ICommand) commandClass.newInstance();
			command.execute(event);
		}
	}

}
